package com.gudong.performance.util;

import com.gudong.performance.service.PerformanceService;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019-04-02 16:27
 */
@Component
public class ExcelUtil {

    @Autowired
    private PerformanceService performanceService;


    /**
     * 生成user表excel
     *
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getUser")
    public String getUser(HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("绩效表");
//        createTitle(workbook, sheet,new Date());
//        List<User> rows = userService.getAll();

        //设置日期格式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
//        for(User user:rows){
//            HSSFRow row = sheet.createRow(rowNum);
//            row.createCell(0).setCellValue(user.getId());
//            row.createCell(1).setCellValue(user.getName());
//            row.createCell(2).setCellValue(user.getUsername());
//            HSSFCell cell = row.createCell(3);
//            cell.setCellValue(user.getCreate_time());
//            cell.setCellStyle(style);
//            rowNum++;
//        }

        String fileName = "导出excel例子.xls";

        //生成excel文件
        buildExcelFile(fileName, workbook);

        //浏览器下载excel
        buildExcelDocument(fileName, workbook, response);

        return "download excel";
    }

    //生成excel文件
    public void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
        FileOutputStream fos = new FileOutputStream(filename);
        workbook.write(fos);
        fos.flush();
        fos.close();
    }

    //浏览器下载excel
    public void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
